package com.lagou.rpc.consumer.balancer;

import com.lagou.rpc.consumer.config.ServerConfig;
import com.lagou.rpc.consumer.config.ServerProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 负载均衡器
 */
@Component
public class LoadBalancer {

    private int index=0;

    @Autowired
    ServerProperties serverProperties;

    /**
     * 通过轮询策略获得一个可用的服务
     * @return
     */
    public ServerConfig getServerConfig(){
        return serverProperties.getConfigs().get(nextIndex());
    }

    /**
     * 获得下一个下标
     * @return
     */
    public synchronized int nextIndex(){
        try {
            return index;
        }finally {
            if(++index>serverProperties.getConfigs().size()-1){
                index=0;
            }
        }
    }


}
